<!--
 * @Description:
 * @version:
 * @Author: mikeJang
 * @Date: 2021-06-15 19:43:26
 * @LastEditors: mikeJang
 * @LastEditTime: 2021-08-25 17:38:10
 * @FilePath: \YU_LIN_Frontend\src\components\SAdcdTreeSingle.vue
-->
<template>
  <a-tree-select size="large"
                 :value="value"
                 :tree-data="treeData"
                 placeholder="请选择"
                 tree-data-simple-mode
                 :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
                 :disabled="disabled"
                 allowClear
                 :load-data="onLoadData"
                 @change="handleChange"
                 show-search
                 :filterTreeNode="filterMethod">
  </a-tree-select>
</template>

<script>

export default {
  name: "SAdcdTreeSingle",
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      treeData: [],
      pid: null
    };
  },
  created () {
    this.getData();
  },
  methods: {
    parseNode (item) {
      return {
        title: item.adnm,
        value: item.adcd,
        id: item.adcd,
        pId: item.padcd,
        children:
          item.hasChild && item.children
            ? item.children.map(it => this.parseNode(it))
            : [],
        isLeaf: item.hasChild ? false : true
      };
    },
    getData () {
        const params = {
          isQueryAll: false,
          pid: this.pid
        }
        this.$http.userauth.queryAdTree(params).then(res => {
          if (res) {
            this.treeData = [this.parseNode(res)];
          }
        });
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        const params = {
          isQueryAll: false,
          pid: treeNode.dataRef.id
        }
        this.$http.userauth.queryAdTree(params).then(res => {
            if (res) {
              const children = res.children.map(item => this.parseNode(item));
              const findFun = item => {
                if (item.id === id) {
                  item.children = children;
                } else if (!item.isLeaf) {
                  item.children.find(it => findFun(it));
                }
              };
              this.treeData.find(node => findFun(node));

              resolve();
            }
          });
      });
    },

    handleChange (val) {
      this.$emit("change", val);
      this.$emit("change-done", val);
    },
    filterMethod (str, node) {
      return ~(node.data.props.title || "").indexOf(str);
    }
  }
};
</script>
